/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-5-18 下午1:46 Created by dwzhang
 */
package com.jade.bss.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.jade.bss.customer.grant.GrantManager;
import com.jade.bss.customer.permission.PermissionEntry;
import com.jade.bss.customer.permission.PermissionGroup;
import com.jade.bss.customer.permission.PermissionManager;
import com.jade.bss.customer.principal.SimplePrincipal;
import com.jade.bss.customer.role.RoleEntry;
import com.jade.bss.customer.role.RoleManager;
import com.jade.bss.base.customer.Customer;
import com.jade.bss.web.vo.PermissionEnterVo;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.CriterionUtils;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.base.util.PagingResult;
import com.jade.framework.base.util.ResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

/**
 * 默认的角色控制器。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a>
 * @version 1.0 15-5-18 下午1:46
 */
@RestController
@RequestMapping (value = "/role", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "角色管理", description = "系统设置--角色管理")
public class RoleController
{
    private RoleManager roleManager = (RoleManager) ApplicationContextUtils.getBean("bss_roleManager");
    private GrantManager grantManager = (GrantManager) ApplicationContextUtils.getBean("bss_grantManager");
    private PermissionManager permissionManager = (PermissionManager) ApplicationContextUtils.getBean("bss_permissionManager");

    //@RequiresAuthentication
    //@RequiresPermissions (value = {"role:view"})
    @RequestMapping (value = "/query", method = RequestMethod.GET)
    @ApiOperation(value = "查询角色", httpMethod = "GET")
    public void queryRole(@ApiParam("角色类型") @RequestParam (value = "type", required = false) String type,
                          @ApiParam("关键词") @RequestParam (value = "keyword", required = false) String keyword,
                          @ApiParam("起始值") @RequestParam (value = "offset", defaultValue = "0") int offset,
                          @ApiParam("每页大小") @RequestParam (value = "length", defaultValue = "10") int length,
                          @ApiParam("排序字段") @RequestParam (value = "sort", required = false) String sort,
                          @ApiParam(value = "排序规则", allowableValues = "desc, asc") @RequestParam (value = "order", required = false) String order,
                          HttpServletResponse response) throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        Criteria criteria = new Criteria(offset, length);
        if (StringUtils.isNotBlank(type)) {
            criteria.add(Restrictions.like("type", type));
        }
        if (StringUtils.isNotBlank(keyword)) {
            criteria.add(Restrictions.like("name", keyword));
        }
        criteria.add(Restrictions.eq("ownerId", customer.getOwnerId()));
        CriterionUtils.addOrder(criteria, sort, order, "id");
        PagingList<RoleEntry> roles = roleManager.queryRole(criteria);
        PagingResult pagingResult = PagingResult.getResult(roles);
        ResponseUtils.writeSuccessPagingResult(response,pagingResult);
    }

    //@RequiresAuthentication
    //@RequiresPermissions (value = {"role:create"})
    @RequestMapping (value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "增加角色", httpMethod = "POST")
    public void addRole(@ApiParam("角色id") @RequestBody RoleEntry roleEntry,HttpServletResponse response)
            throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        roleEntry.setOwnerId(customer.getOwnerId());
        roleManager.addRole(roleEntry);
        ResponseUtils.writeSuccessResult(response);
    }

    @RequiresAuthentication
    //@RequiresPermissions (value = {"role:remove"})
    @RequestMapping (value = "/remove/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除角色", httpMethod = "DELETE")
    public void removeRole(@ApiParam("角色id") @PathVariable ("id") int[] ids, HttpServletResponse response)
            throws Exception
    {
        roleManager.removeRoles(ids);
        ResponseUtils.writeSuccessResult(response);
    }
   
    //@RequiresAuthentication
    //@RequestMapping (value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "角色标识", httpMethod = "GET")
    public void get(@ApiParam("角色id") @PathVariable int id, HttpServletResponse response) throws Exception
    {
        RoleEntry role = roleManager.getRole(id);
        ResponseUtils.writeSuccessResult(response,role);
    }
   
    //@RequiresAuthentication
    @RequiresPermissions (value = {"role_update"})
    @RequestMapping (value = "/edit", method = RequestMethod.PUT)
    @ApiOperation(value = "编辑角色", httpMethod = "PUT")
    public void editRole(@ApiParam("角色对象") @RequestBody RoleEntry role, HttpServletResponse response)
            throws Exception
    {
        RoleEntry roleEntry = roleManager.getRole(role.getId());
        if (roleEntry != null) {
            roleEntry.setName(role.getName());
            roleEntry.setStatus(role.getStatus());
            roleEntry.setDescription(role.getDescription());
            roleManager.updateRole(roleEntry);
        }
        ResponseUtils.writeSuccessResult(response);
    }

   
    //@RequiresAuthentication
    @RequestMapping (value = "/grantRoleList/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "权限列表", httpMethod = "GET")
    public void listPermission(@ApiParam("角色id") @PathVariable String id,HttpServletResponse response)
            throws Exception
    {
        Map<String, List<PermissionEnterVo>> rolePermissionMap = new HashMap<String, List<PermissionEnterVo>>();
        //取所有的权限
        List<PermissionEntry> permissions = permissionManager.listPermission();
        List<PermissionGroup> groups = permissionManager.listGroup();
        //取role的权限
        SimplePrincipal principal = new SimplePrincipal();
        principal.setName(id);
        principal.setType(SimplePrincipal.TYPE_ROLE);
        List<PermissionEntry> rolePermissions = grantManager.getPermissions(principal);
        for (PermissionEntry permissionEntry : permissions) {
            String groupName = null;
            for (PermissionGroup permissionGroup : groups) {
                if (permissionEntry.getGroupId() == permissionGroup.getId()) {
                    groupName = permissionGroup.getName();
                    break;
                }
            }
            List<PermissionEnterVo> list = rolePermissionMap.get(groupName);
            if (list == null) {
                list = new ArrayList<PermissionEnterVo>();
                rolePermissionMap.put(groupName, list);
            }
            PermissionEnterVo permissionEnterVo = new PermissionEnterVo();
            permissionEnterVo.setPermissionId(permissionEntry.getId());
            permissionEnterVo.setPermissionName(permissionEntry.getName());
            permissionEnterVo.setDisplayName(permissionEntry.getDisplayName());
            for (PermissionEntry rolePermission : rolePermissions) {
                if (permissionEntry.getId() == rolePermission.getId()) {
                    permissionEnterVo.setChecked(true);
                    break;
                }
            }
            list.add(permissionEnterVo);
        }
        HashMap result = new HashMap();
        result.put("rolePerMap",rolePermissionMap);
        result.put("roleId",id);
        ResponseUtils.writeSuccessResult(response,result);
    }

   
    //@RequiresAuthentication
    @RequiresPermissions (value = {"role:grant"})
    @RequestMapping (value = "/grantRole", method = RequestMethod.GET)
    @ApiOperation(value = "角色授权", httpMethod = "GET")
    public void grantPermission(@ApiParam("权限id") @RequestParam (value = "perId", required = false) int[] perIds,
                                @ApiParam("角色id") @RequestParam ("roleId") String roleId, HttpServletResponse response)
            throws Exception
    {
        SimplePrincipal principal = new SimplePrincipal();
        principal.setName(roleId);
        principal.setType(SimplePrincipal.TYPE_ROLE);
        grantManager.revokePermissions(principal);
        if (perIds != null && perIds.length > 0) {
            grantManager.setPermissions(principal, perIds);
        }
        ResponseUtils.writeSuccessResult(response);
    }

   
    @RequestMapping (value = "/listRole", method = RequestMethod.GET)
    @ApiOperation(value = "角色列表", httpMethod = "GET")
    public void listRole(@ApiParam("角色类型") @RequestParam (value = "type", required = false) String type, HttpServletResponse response)
            throws Exception
    {
        if (StringUtils.isBlank(type)) {
            ResponseUtils.writeSuccessResult(response, roleManager.listRole());
        }
        else {
            ResponseUtils.writeSuccessResult(response, roleManager.listRole(type));
        }
    }
}
